<?php


namespace app\admin\controller\Coupon;


use app\admin\controller\BaseController;
use app\admin\model\Coupon\CouponModel;
use app\admin\model\Course\CourseModel;
use app\admin\model\Goods\GoodsModel;
use app\Request;
use app\Utils\Util;
use Exception;
use think\facade\Db;

class Coupon extends BaseController
{
    /**
     * 分页
     * @param Request $request
     * @return array
     */
    public function getCouponList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;
        $coupon_title = !empty($param['coupon_title']) ? $param['coupon_title'] : "";
        $is_show = !empty($param['is_show']) ? $param['is_show'] : "";
        if (!empty($coupon_title)) {
            array_push($where, ['coupon_title', 'like', '%' . $coupon_title . '%']);
        }
        if (!empty($is_show)) {
            if ($is_show == 1) {
                array_push($where, ['is_show', '=', 1]);
            }
            if ($is_show == 2) {
                array_push($where, ['is_show', '=', 0]);
            }
        }
        $list = CouponModel::getCouponListWhere($page, $limit, $where);
        $count = CouponModel::getCouponCountWhere($where);
        foreach ($list as &$item){
            $item['time'] = date("Y-m-d",strtotime($item['start_time'])). ' & '.date("Y-m-d",strtotime($item['end_time']));
        }
        return Util::returnPageJson(self::CODE_DATA, $count, $list, "");
    }

    /**
     * 添加优惠券
     * @param Request $request
     * @return array
     */
    public function addCoupon(Request $request)
    {
        $param = $request->param();
        $time = explode("&",$param['time']);
        $start_time = date("Y-m-d 00:00:00",strtotime($time[0]));
        $end_time = date("Y-m-d 23:59:59",strtotime($time[1]));
        $data = [
            'coupon_title' => !empty($param['coupon_title']) ? $param['coupon_title'] : "",
            'label' => !empty($param['label']) ? $param['label'] : 0,
            'mer_id' => !empty($param['mer_id']) ? $param['mer_id'] : 0,
            'attr' => !empty($param['attr']) ? $param['attr'] : 0,
            'type' => !empty($param['type']) ? $param['type'] : 0,
            'goods_ids' => !empty($param['select']) ? $param['select'].',' : "",
            'amount' => !empty($param['amount']) ? $param['amount'] : 0,
            'total_amount' => !empty($param['total_amount']) ? $param['total_amount'] : 0,
            'total_num' => !empty($param['total_num']) ? $param['total_num'] : 0,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'up_time' => date("Y-m-d H:i:s",time()),
            'add_time' => date("Y-m-d H:i:s",time())
        ];
        if (!empty($param['is_infinite']) && $param['is_infinite'] == "on") {
            $save['is_infinite'] = 1;
        }else{
            $save['is_infinite'] = 0;
        }
        if (!empty($param['is_level']) && $param['is_level'] == "on") {
            $save['is_level'] = 1;
        }else{
            $save['is_level'] = 0;
        }
        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $data['is_show'] = 1;
        }else{
            $data['is_show'] = 0;
        }
        Db::startTrans();
        try{
            $id = CouponModel::addCoupon($data);
            if ($id) {
                DB::commit();
                return Util::returnJson(self::CODE_SUCCESS, null, "添加成功");
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "添加失败2");
            }
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "添加失败1");
        }
    }

    /**
     * 编辑优惠券
     * @param Request $request
     * @return array
     */
    public function editCoupon(Request $request)
    {
        $param = $request->param();
        $id = !empty($param['id']) ? $param['id'] : 0;
        $time = explode("&",$param['time']);
        $start_time = date("Y-m-d 00:00:00",strtotime($time[0]));
        $end_time = date("Y-m-d 23:59:59",strtotime($time[1]));
        $save = [
            'coupon_title' => !empty($param['coupon_title']) ? $param['coupon_title'] : "",
            'label' => !empty($param['label']) ? $param['label'] : 0,
            'mer_id' => !empty($param['mer_id']) ? $param['mer_id'] : 0,
            'attr' => !empty($param['attr']) ? $param['attr'] : 0,
            'type' => !empty($param['type']) ? $param['type'] : 0,
            'goods_ids' => !empty($param['select']) ? $param['select'].',' : "",
            'amount' => !empty($param['amount']) ? $param['amount'] : 0,
            'total_amount' => !empty($param['total_amount']) ? $param['total_amount'] : 0,
            'total_num' => !empty($param['total_num']) ? $param['total_num'] : 0,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'up_time' => date("Y-m-d H:i:s",time())
        ];
        if (!empty($param['is_infinite']) && $param['is_infinite'] == "on") {
            $save['is_infinite'] = 1;
        }else{
            $save['is_infinite'] = 0;
        }
        if (!empty($param['is_level']) && $param['is_level'] == "on") {
            $save['is_level'] = 1;
        }else{
            $save['is_level'] = 0;
        }
        if (!empty($param['is_show']) && $param['is_show'] == "on") {
            $save['is_show'] = 1;
        }else{
            $save['is_show'] = 0;
        }
        Db::startTrans();
        try{
            $flag = CouponModel::updateCouponWhere([['id','=',$id]],$save);
            if ($flag) {
                DB::commit();
                return Util::returnJson(self::CODE_SUCCESS, null, "修改成功");
            } else {
                DB::rollBack();
                return Util::returnJson(self::CODE_ERROR, null, "修改失败2");
            }
        }catch (Exception $e){
            DB::rollBack();
            return Util::returnJson(self::CODE_ERROR, null, "修改失败1");
        }
    }


    /**
     * 获取商品或课程
     * @param Request $request
     * @return array
     */
    public function getGoodsCourseAll(Request $request)
    {
        $param = $request->param();
        $label = !empty($param['label']) ? $param['label'] : 0;
        if(!empty($param['coupon_id'])){
            $coupon = CouponModel::getCouponWhere([['id','=',$param['coupon_id']]],'label,goods_ids');
            if(!empty($coupon)){
                $goods_ids = [];
                if(!empty($coupon['label'])){
                    if($coupon['label'] == $label){
                        $goods_ids = explode(',',trim($coupon['goods_ids'],','));
                    }
                }
            }
        }
        if(!empty($label)){
            $list = [];
            if($label == 1){
                $list = CourseModel::getCourseWhereMore([['is_show','=',1],['is_del','=',0]]);
            }
            if($label == 2){
                $list = GoodsModel::getGoodsWhereMore([['is_show','=',1],['is_del','=',0]]);
            }
            $data = [];
            foreach ($list as $item){
                if($label == 1){
                    $arr['name'] = $item['title'];
                }
                if($label == 2){
                    $arr['name'] = $item['good_name'];
                }
                $arr['value'] = $item['id'];
                if(!empty($goods_ids)){
                    if(in_array($item['id'],$goods_ids)){
                        $arr['selected'] = true;
                    }else{
                        $arr['selected'] = false;
                    }
                }else{
                    $arr['selected'] = false;
                }
                array_push($data,$arr);
            }
        }
        return Util::returnJson(self::CODE_SUCCESS,$data);
    }

}